package com.zhiyou.app.shop.website.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.website.dao.IActivityApplyDao;
import com.zhiyou.app.shop.website.dao.ILoveFoundDao;
import com.zhiyou.app.shop.website.dao.IMoneyDealDao;
import com.zhiyou.app.shop.website.dao.IMsgDao;
import com.zhiyou.app.shop.website.dao.ITransferInfoDao;
import com.zhiyou.app.shop.website.dao.IUserAccountDao;
import com.zhiyou.app.shop.website.dao.IUserInfoDao;
import com.zhiyou.app.shop.website.dao.IUserStockInfoDao;
import com.zhiyou.app.shop.website.dao.pojo.ActivityApply;
import com.zhiyou.app.shop.website.dao.pojo.DicItem;
import com.zhiyou.app.shop.website.dao.pojo.LoveFound;
import com.zhiyou.app.shop.website.dao.pojo.MoneyDeal;
import com.zhiyou.app.shop.website.dao.pojo.Msg;
import com.zhiyou.app.shop.website.dao.pojo.TransferInfo;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserAccount;
import com.zhiyou.app.shop.website.dao.pojo.UserStockInfo;
import com.zhiyou.app.shop.website.service.IDicItemService;
import com.zhiyou.app.shop.website.service.IPlayService;
import com.zhiyou.app.shop.website.service.IUserAccountService;
import com.zhiyou.app.shop.website.service.IUserStockService;

@Service(value="playService")
public class PlayServiceImpl implements IPlayService {
	
	@Autowired
	private IUserInfoDao userInfoDao;
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private IUserAccountDao userAccountDao;
	@Autowired
	private ITransferInfoDao transferInfoDao;
	@Autowired
	private IDicItemService dicItemService;
	@Autowired
	private IMoneyDealDao moneyDealDao;
	@Autowired
	private IMsgDao msgDao;
	@Autowired
	private IActivityApplyDao activityApplyDao;
	@Autowired
	private ILoveFoundDao loveFoundDao;
	@Autowired
	private IUserStockInfoDao userStockInfoDao;
	@Autowired
	private IUserStockService userStockService;

	public void doExchange(String userId, BigDecimal amount, String type) {
		User user = userInfoDao.findById(userId);
		UserAccount userAccount = userAccountService.findUserAccount(user.getUserAccount());
		MoneyDeal moneyDealImport = new MoneyDeal();
		MoneyDeal moneyDealExport = new MoneyDeal();
		Long date = new Date().getTime();
		DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.TRANSFER_TYPE, type);
		//转出
		moneyDealExport.setUserId(user.getUserId());
		moneyDealExport.setCreateDate(new Timestamp(date));
		moneyDealExport.setPay(amount);
		moneyDealExport.setSubjectType("2");
		moneyDealExport.setAccountSubject(dicItem.getName());
		//转入
		moneyDealImport.setUserId(user.getUserId());
		moneyDealImport.setCreateDate(new Timestamp(date));
		moneyDealImport.setIncome(amount);
		moneyDealImport.setSubjectType("2");
		moneyDealImport.setAccountSubject(dicItem.getName());
		
		//账户兑换   并记流水账
		if("1".equals(type)){  //奖金转股票    奖金账户减去    股金账户加上  股金自动换算成股票  
			List<DicItem> stockFlagList = dicItemService.findByType(ShopConstants.STOCK_FLAG);
			DicItem stockFlag = new DicItem();
			if(stockFlagList != null && stockFlagList.size() >0){
				stockFlag = stockFlagList.get(0);
			}
			if("0".equals(stockFlag.getCode())){  //股票停盘中     不买股票 生成股金
				if(userAccount.getStockMoney() != null){
					userAccount.setStockMoney(userAccount.getStockMoney().add(amount));  //游戏豆							
				}else{
					userAccount.setStockMoney(amount);
				}
				userAccount.setStockMoney(userAccount.getStockMoney().add(amount));
			}else if("1".equals(stockFlag.getCode())){  //买成股票没有股金了
				userStockService.buyStock(user.getUserAccount(),amount.floatValue());  //股票	
				MoneyDeal buyStockDeal= new MoneyDeal();
				buyStockDeal.setAccountSubject("自动购买股票");
				buyStockDeal.setAccountType(ShopConstants.STOCK);
				buyStockDeal.setCreateDate(new Timestamp(date));
				buyStockDeal.setUserId(userId);
				buyStockDeal.setSubjectType("5");
				buyStockDeal.setPay(amount);
				moneyDealDao.save(buyStockDeal);
			}
			userAccount.setBonusMoney(userAccount.getBonusMoney().subtract(amount));
			moneyDealExport.setAccountType(ShopConstants.PRIZE);
			moneyDealImport.setAccountType(ShopConstants.STOCK);
		}else if("2".equals(type)){  //奖金转激活
			userAccount.setBonusMoney(userAccount.getBonusMoney().subtract(amount));
			userAccount.setActivMoney(userAccount.getActivMoney().add(amount));
			moneyDealExport.setAccountType(ShopConstants.PRIZE);
			moneyDealImport.setAccountType(ShopConstants.ACTIVITY);
		}else if("3".equals(type)){  //激活转附属
			userAccount.setActivMoney(userAccount.getActivMoney().subtract(amount));
			userAccount.setAdditionMoney(userAccount.getAdditionMoney().add(amount));
			moneyDealExport.setAccountType(ShopConstants.ACTIVITY);
			moneyDealImport.setAccountType(ShopConstants.ADD);
		}else if("4".equals(type)){  //重消转股票  ---改成 --咖啡转仙草（奖金转重消）
			userAccount.setBonusMoney(userAccount.getBonusMoney().subtract(amount));
			userAccount.setConsumerMoney(userAccount.getConsumerMoney().add(amount));
			moneyDealExport.setAccountType(ShopConstants.PRIZE);
			moneyDealImport.setAccountType(ShopConstants.RESUMER);
		}
		moneyDealDao.save(moneyDealExport);
		moneyDealDao.save(moneyDealImport);
		userAccountDao.save(userAccount);
	}

	public void getMoneyDeal(Page page, MoneyDeal moneyDeal) {
		moneyDealDao.findByExample(page, moneyDeal, Order.desc("createDate"));
	}

	public void doConvert(String userId, String toUserId, BigDecimal amount) {
		User user = userInfoDao.findById(userId);
		UserAccount userAccount = userAccountService.findUserAccount(user.getUserAccount());
		
		User touser = userInfoDao.findById(toUserId);
		UserAccount touserAccount = userAccountService.findUserAccount(touser.getUserAccount());
		Long date = new Date().getTime();
		//数据字典中的转账 手续费率
		/*DicItem dicItem = null;
		List<DicItem> dicList = dicItemService.findByType(ShopConstants.MUTUAL_CONVERSION);
		if(dicList != null && dicList.size() > 0){
			dicItem = dicList.get(0);
		}*/
		//手续费
		//BigDecimal fee = amount.multiply(new BigDecimal(dicItem.getCode()));
		userAccount.setActivMoney(userAccount.getActivMoney().subtract(amount));
		touserAccount.setActivMoney(touserAccount.getActivMoney().add(amount));
		
		TransferInfo transferInfo = new TransferInfo();
		transferInfo.setUserId(user.getUserAccount());
		transferInfo.setFee(BigDecimal.ZERO);
		transferInfo.setAmount(amount);
		transferInfo.setPostTime(new Timestamp(date));
		transferInfo.setToUserId(touser.getUserAccount());
		transferInfo.setType("互转");
		transferInfo.setAccountType("互转");
		transferInfoDao.save(transferInfo);
		
/*		MoneyDeal moneyDeal = new MoneyDeal();
		moneyDeal.setUserId(userId);
		moneyDeal.setCreateDate(new Timestamp(date));
		moneyDeal.setPay(fee);
		moneyDeal.setAccountSubject("激活豆转出手续费");
		moneyDeal.setSubjectType("3");
		moneyDeal.setAccountType(ShopConstants.ACTIVITY);
		moneyDealDao.save(moneyDeal);*/
		
		MoneyDeal moneyDealin = new MoneyDeal();
		moneyDealin.setUserId(userId);
		moneyDealin.setCreateDate(new Timestamp(date));
		moneyDealin.setPay(amount);
		moneyDealin.setAccountSubject("激活豆转出");
		moneyDealin.setSubjectType("3");
		moneyDealin.setAccountType(ShopConstants.ACTIVITY);
		moneyDealin.setRemark(touser.getUserAccount());
		moneyDealDao.save(moneyDealin);
		
		MoneyDeal moneyDealout = new MoneyDeal();
		moneyDealout.setUserId(toUserId);
		moneyDealout.setCreateDate(new Timestamp(date));
		moneyDealout.setIncome(amount);
		moneyDealout.setAccountSubject("激活豆转入");
		moneyDealout.setSubjectType("3");
		moneyDealout.setAccountType(ShopConstants.ACTIVITY);
		moneyDealout.setRemark(user.getUserAccount());
		moneyDealDao.save(moneyDealout);
	/*	
		Msg msg = new Msg();
		msg.setCreateDate(new Timestamp(date));
		msg.setFlag(ShopConstants.TRUE);
		msg.setMsg("账户 "+user.getUserAccount()+" 通过互转中心给您转"+amount+"个激活豆，已经到账");
		msg.setReceiveId(touser.getUserAccount());
		msg.setSendId(user.getUserAccount());
		msg.setTitle("激活豆转入账户的消息");
		msg.setType("1");//邮件
		msgDao.save(msg);
		*/
		userAccountDao.save(userAccount);
		userAccountDao.save(touserAccount);
	}
	
	public void doVvconvert(String userId, String toUserId, BigDecimal amount, String type){
		User user = userInfoDao.findById(userId);
		UserAccount userAccount = userAccountService.findUserAccount(user.getUserAccount());
		
		User touser = userInfoDao.findById(toUserId);
		UserAccount touserAccount = userAccountService.findUserAccount(touser.getUserAccount());
		Long date = new Date().getTime();
		String accountType  = null;
		String accountSubject = null;
		
		if("1".equals(type)){ //激活
			accountType = ShopConstants.ACTIVITY;
			accountSubject = "激活豆";
			userAccount.setActivMoney(userAccount.getActivMoney().subtract(amount));
			touserAccount.setActivMoney(touserAccount.getActivMoney().add(amount));
		}else if("2".equals(type)){ //奖金
			accountType = ShopConstants.PRIZE;
			accountSubject = "咖啡豆";
			userAccount.setBonusMoney(userAccount.getBonusMoney().subtract(amount));
			touserAccount.setBonusMoney(touserAccount.getBonusMoney().add(amount));
		}else if("3".equals(type)){ //游戏
			accountType = ShopConstants.STOCK;
			accountSubject = "游戏豆";
			userAccount.setStockMoney(userAccount.getStockMoney().subtract(amount));
			touserAccount.setStockMoney(touserAccount.getStockMoney().add(amount));
		}
		
		TransferInfo transferInfo = new TransferInfo();
		transferInfo.setUserId(user.getUserAccount());
		transferInfo.setAmount(amount);
		transferInfo.setPostTime(new Timestamp(date));
		transferInfo.setToUserId(touser.getUserAccount());
		transferInfo.setType("VV账户互转");
		transferInfo.setAccountType(accountSubject);
		transferInfoDao.save(transferInfo);
		
		MoneyDeal moneyDealin = new MoneyDeal();
		moneyDealin.setUserId(userId);
		moneyDealin.setCreateDate(new Timestamp(date));
		moneyDealin.setPay(amount);
		moneyDealin.setAccountSubject(accountSubject+"转出");
		moneyDealin.setSubjectType("3");
		moneyDealin.setAccountType(accountType);
		moneyDealin.setRemark(touser.getUserAccount());
		moneyDealDao.save(moneyDealin);
		
		MoneyDeal moneyDealout = new MoneyDeal();
		moneyDealout.setUserId(toUserId);
		moneyDealout.setCreateDate(new Timestamp(date));
		moneyDealout.setIncome(amount);
		moneyDealout.setAccountSubject(accountSubject+"转入");
		moneyDealout.setSubjectType("3");
		moneyDealout.setAccountType(accountType);
		moneyDealout.setRemark(user.getUserAccount());
		moneyDealDao.save(moneyDealout);
		
		userAccountDao.save(userAccount);
		userAccountDao.save(touserAccount);
		
		
	}

	public void saveApplyActivi(ActivityApply apply) {
		activityApplyDao.save(apply);
		
	}

	public void saveLoveFound(LoveFound loveFound) {
		Msg msg = new Msg();
		msg.setCreateDate(loveFound.getCreateDate());
		msg.setFlag(ShopConstants.TRUE);
		msg.setIsRead(ShopConstants.FALSE);
		msg.setSendId(loveFound.getUserId());
		msg.setTitle(loveFound.getUserId()+"申请爱心基金"); //标题
		msg.setMsg("会员"+loveFound.getUserId()+"申请"+loveFound.getLoveAmount()+"元爱心基金");  //内容
		List<User> userList = userInfoDao.findByProperty("role", ShopConstants.ADMIN);
		if(userList != null && userList.size() > 0){
			User user = userList.get(0);
			msg.setReceiveId(user.getUserAccount());
		}
		msgDao.save(msg);
		loveFoundDao.save(loveFound);
		
	}

	/**
	 * @param userId 用户id
	 * @param amount  股票数量
	 * @param type  买入  沽出
	 */
	public void doStockTrade(String userId, Integer stockQuantity,BigDecimal price, String type) {
		User user = userInfoDao.findById(userId);
		UserAccount  account = userAccountService.findByUserAccount(user.getUserAccount());
		//Long date = System.currentTimeMillis();
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		if("0".equals(type)){   //买入   用什么买    股金
			account.setStockNum(account.getStockNum()+stockQuantity);
			account.setStockMoney(account.getStockMoney().subtract(new BigDecimal(stockQuantity).multiply(price)));
			userAccountDao.update(account);
			UserStockInfo userStockInfo = new UserStockInfo();
			userStockInfo.setCreateDate(timestamp);
			userStockInfo.setPrice(price);
			userStockInfo.setStockQuantity(stockQuantity);
			userStockInfo.setTotalPrice(new BigDecimal(stockQuantity).multiply(price));
			userStockInfo.setTradeDate(timestamp);
			userStockInfo.setType(type);
			userStockInfo.setStatus("1");  //交易成功
			userStockInfo.setUserId(user.getUserAccount());
			userStockInfoDao.save(userStockInfo);
			
			MoneyDeal deal = new MoneyDeal();
			deal.setAccountSubject("股票购买");
			deal.setAccountType(ShopConstants.STOCK);
			deal.setCreateDate(timestamp);
			deal.setPay(new BigDecimal(stockQuantity).multiply(price));
			deal.setSubjectType("5");
			deal.setUserId(user.getUserAccount());
			moneyDealDao.save(deal);
			
		}else if("1".equals(type)){  // 沽出
			//手续费  8%
			BigDecimal amount = new BigDecimal(stockQuantity).multiply(price);
			BigDecimal fee = amount.multiply(new BigDecimal(0.08));
			//92% 的 30% 的股金
			BigDecimal stock = amount.multiply(new BigDecimal(0.92)).multiply(new BigDecimal(0.3));
			//92% 的 70% 的50% 作为奖金币
			BigDecimal prize = amount.multiply(new BigDecimal(0.92)).multiply(new BigDecimal(0.7)).multiply(new BigDecimal(0.5));
			//92% 的 70% 的50% 作为加单 vv豆
			BigDecimal add = amount.multiply(new BigDecimal(0.92)).multiply(new BigDecimal(0.7)).multiply(new BigDecimal(0.5));
			account.setStockNum(account.getStockNum()-stockQuantity);
			account.setStockMoney(account.getStockMoney().add(stock));
			account.setBonusMoney(account.getBonusMoney().add(prize));
			account.setAdditionMoney(account.getAdditionMoney().add(add));
			userAccountDao.update(account);
			UserStockInfo userStockInfo = new UserStockInfo();
			userStockInfo.setCreateDate(timestamp);
			userStockInfo.setPrice(price);
			userStockInfo.setStockQuantity(stockQuantity);
			userStockInfo.setTotalPrice(new BigDecimal(stockQuantity).multiply(price));
			userStockInfo.setTradeDate(timestamp);
			userStockInfo.setType(type);
			userStockInfo.setUserId(user.getUserAccount());
			userStockInfo.setStatus("1");  //交易成功
			userStockInfoDao.save(userStockInfo);
			
			MoneyDeal moneyFee = new MoneyDeal();
			//MoneyDeal moneystockSale = new MoneyDeal();
			MoneyDeal moneystockadd = new MoneyDeal();
			MoneyDeal moneyPrize = new MoneyDeal();
			MoneyDeal moneyAdd = new MoneyDeal();
			moneyFee.setUserId(userId);
			moneyFee.setAccountSubject("沽出股票手续费");
			moneyFee.setAccountType(ShopConstants.STOCK);
			moneyFee.setSubjectType("5");
			moneyFee.setCreateDate(timestamp);
			moneyFee.setPay(fee);
			
			moneystockadd.setUserId(userId);
			moneystockadd.setAccountSubject("沽出股票所得股金");
			moneystockadd.setAccountType(ShopConstants.STOCK);
			moneystockadd.setSubjectType("5");
			moneystockadd.setCreateDate(timestamp);
			moneystockadd.setIncome(stock);
			
			moneyPrize.setUserId(userId);
			moneyPrize.setAccountSubject("沽出股票所得奖金");
			moneyPrize.setAccountType(ShopConstants.PRIZE);
			moneyPrize.setSubjectType("5");
			moneyPrize.setCreateDate(timestamp);
			moneyPrize.setIncome(prize);
			
			moneyAdd.setUserId(userId);
			moneyAdd.setAccountSubject("沽出股票所得加单");
			moneyAdd.setAccountType(ShopConstants.ADD);
			moneyAdd.setSubjectType("5");
			moneyAdd.setCreateDate(timestamp);
			moneyAdd.setIncome(add);
			//moneyDealDao.save(moneystockSale);
			moneyDealDao.save(moneyFee);
			moneyDealDao.save(moneystockadd);
			moneyDealDao.save(moneyPrize);
			moneyDealDao.save(moneyAdd);
		}
	}

	public void findExchangeDeal(String userId, String subjectType) {
		// TODO Auto-generated method stub
		
	}

	public void findTransfer(Page page, String userAccount, String type) {
		DetachedCriteria criteria = DetachedCriteria.forClass(TransferInfo.class);  
		if(userAccount != null && !"".equals(userAccount)){
			criteria.add(Expression.eq("userId", userAccount));
		}
		if(type != null && !"".equals(type)){
			criteria.add(Expression.eq("type", type));
		}
		transferInfoDao.findByCriteria(page, criteria, Order.desc("postTime"));
	}

	public void findApplyActivity(Page page, String userAccount, String status) {
		DetachedCriteria criteria = DetachedCriteria.forClass(ActivityApply.class);
		if(userAccount != null && !"".equals(userAccount)){
			criteria.add(Expression.eq("applyId", userAccount));
		}
		if(status != null && !"".equals(status)){
			criteria.add(Expression.eq("status", status));
		}
		activityApplyDao.findByCriteria(page, criteria, Order.desc("applyDate"));
	}

	public ActivityApply findById(String id) {
		return activityApplyDao.findById(id);
	}

	public void updateApply(ActivityApply apply) {
		activityApplyDao.update(apply);
	}

	public List findTransfer(String userAccount,
			int startNum, int pagesize) {
		return transferInfoDao.findTransfer(userAccount, startNum, pagesize);
	}

	public int findTransferCnt(String userAccount) {
		return transferInfoDao.findTransferCnt(userAccount);
	}

	
}
